﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Chromos.Actors;

namespace Chromos.ActionEngine
{
	public abstract class VisualAction : Action
	{
		// Animation
		private List<String> imageURIs = new List<String>(2);
		protected List<Texture2D> images = new List<Texture2D>(2);
        public List<float[]> offsets = new List<float[]>(2);
		protected int currentImageIndex = 0;
		/// <summary>
		/// Delay in ms between frames of current animation
		/// </summary>
		protected int animDelay;
		protected int delayTotal = 0;
		protected Vector2 offset = Vector2.Zero;

		public VisualAction(Actor actor, ContentManager content, Vector2 force, ForceType forceType, int animDelay)
			: base(actor, content, force, forceType)
		{
			this.animDelay = animDelay;
		}

		public override void load()
		{
			foreach (String s in imageURIs)
			{
				images.Add(content.Load<Texture2D>(s));
			}
		}
		// Adds a string to the list of images to load
		public void addImageToLoad(String uri)
		{
			imageURIs.Add(uri);
            offsets.Add(new float[2]);
		}

		public override void act()
		{
			animate();
		} 

		protected void animate()
		{
			delayTotal += actor.game.timeSinceLastUpdate;
			if (delayTotal >= animDelay)
			{
				delayTotal = 0;
				incrementCurrentImage();
			}
		}
		public Texture2D getCurrentImage()
		{
			return images.ElementAt(currentImageIndex);
		}
		Vector2 tempOffset;
		public void incrementCurrentImage()
		{
			// Check for if we need to adjust actor position based on new image dimensions
            tempOffset.X = (offsets.ElementAt((currentImageIndex + 1) % offsets.Count)[0] - offsets.ElementAt(currentImageIndex)[0]);
                //(images.ElementAt((currentImageIndex + 1) % images.Count).Width - images.ElementAt(currentImageIndex).Width);
            tempOffset.Y = (offsets.ElementAt((currentImageIndex + 1) % offsets.Count)[1] - offsets.ElementAt(currentImageIndex)[1]);
                //(images.ElementAt((currentImageIndex + 1) % images.Count).Height - images.ElementAt(currentImageIndex).Height);
			offset.X += tempOffset.X;
			offset.Y -= tempOffset.Y;
			actor.position.X += tempOffset.X;
			actor.position.Y -= tempOffset.Y;

			currentImageIndex++;
			currentImageIndex %= images.Count;
		}

		public override void start()
		{
			applyForce();
		}
		public override void stop()
		{
			currentImageIndex = 0;
			unapplyForce();
			actor.position.X -= offset.X;
			actor.position.Y -= offset.Y;
			offset.X = offset.Y = 0;
		}
		public override void stopWithForce()
		{
			currentImageIndex = 0;
			actor.position.X -= offset.X;
			actor.position.Y -= offset.Y;
			offset.X = offset.Y = 0;
		}
	}
}
